package com.duojuhe.coremodule.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.duojuhe.cache.SystemDictCache;
import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.annotation.KeyLock;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.SingleStringConstant;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.coremodule.sms.enums.SmsEnum;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.redis.redisson.RedisSonLockUtils;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.dateutils.DateUtils;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.common.utils.regexutil.RegexUtil;
import com.duojuhe.common.utils.thread.ThreadUtils;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.sms.entity.*;
import com.duojuhe.coremodule.sms.mapper.*;
import com.duojuhe.common.extend.form.attribute.AttributeParameter;
import com.duojuhe.coremodule.sms.pojo.record.SmsRepeatRecordDto;
import com.duojuhe.coremodule.sms.pojo.sendtask.*;
import com.duojuhe.coremodule.sms.pojo.sendtask.detail.QuerySmsSendTaskDetailReq;
import com.duojuhe.coremodule.sms.pojo.sendtask.detail.QuerySmsSendTaskDetailRes;
import com.duojuhe.coremodule.sms.service.HandlerSmsService;
import com.duojuhe.coremodule.sms.service.SmsSendTaskService;
import com.duojuhe.coremodule.system.entity.SystemDict;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SmsSendTaskServiceImpl extends BaseService implements SmsSendTaskService {
    @Resource
    private SystemDictCache systemDictCache;
    @Resource
    public HandlerSmsService handlerSmsService;
    @Resource
    private SmsIspMapper smsIspMapper;
    @Resource
    private SmsTemplateMapper smsTemplateMapper;
    @Resource
    private SmsChannelMapper smsChannelMapper;
    @Resource
    private SmsSendTaskDetailMapper smsSendTaskDetailMapper;
    @Resource
    private SmsSendTaskMapper smsSendTaskMapper;



    /**
     * 【分页查询】根据条件查询短信发送任务list
     * @param req
     * @return*/
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QuerySmsSendTaskPageRes>>> querySmsSendTaskPageResList(QuerySmsSendTaskPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "createTime desc, taskId desc");
        List<QuerySmsSendTaskPageRes> list = smsSendTaskMapper.querySmsSendTaskPageResList(req);
        list.forEach(this::setHandleSmsSendTaskDictNameColor);
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 根据任务id查询任务明细
     * @param req
     * @return
     */
    @Override
    public ServiceResult<QuerySmsSendTaskRes> querySmsSendTaskResBySendTaskId(SmsSendTaskIdReq req) {
        QuerySmsSendTaskRes res = smsSendTaskMapper.querySmsSendTaskResBySendTaskId(req.getTaskId());
        if (res==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //设置任务内容，组装成逗号分隔形状
        List<QuerySmsSendTaskDetailRes> detailResList = smsSendTaskDetailMapper.querySmsSendTaskDetailResListByTaskId(res.getTaskId());
        //任务内容
        String taskContent = detailResList.stream().map(QuerySmsSendTaskDetailRes::getMobileNumber).collect(Collectors.joining(SingleStringConstant.COMMA));
        res.setTaskContent(taskContent);
        return ServiceResult.ok(res);
    }

    /**
     * 【保存】短信发送任务
     * @param req
     * @return*/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult saveSmsSendTask(SaveSmsSendTaskReq req) {
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
         //检查短信发送任务名称
        checkSmsSendTaskName(req.getTaskName(),userTokenInfoVo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        //发送部门id
        String createDeptId = userTokenInfoVo.getCreateDeptId();
        //任务id
        String taskId = UUIDUtils.getUUID32();
        //发送内容
        BuildSmsSendTaskDto smsSendTaskDto = buildSmsSendTaskDto(taskId,nowDate,req);
        //待发送明细
        List<SmsSendTaskDetail> taskDetailList = smsSendTaskDto.getSuccessContentList();
        if (taskDetailList.isEmpty()){
            return ServiceResult.fail(ErrorCodes.SMS_SEND_TASK_DETAIL_ERROR);
        }
        //检查短信模板
        SmsTemplate smsTemplate = getSmsTemplateByTemplateId(req.getTemplateId());
        //检查渠道
        SmsChannel smsChannel = getSmsChannelByIspId(smsTemplate.getChannelId());
        //检查服务商是否存在
        SmsIsp smsIsp = getSmsIspByIspId(smsChannel.getIspId());
        //当前登录人id
        String userId = userTokenInfoVo.getUserId();
        //发送类型
        String taskTypeCode = req.getTaskTypeCode();
        //发送类型
        String taskType = SmsEnum.SmsSendTaskType.SMS_IMMEDIATELY_SEND.getKey();
        //发送状态
        String taskStatusCode = SmsEnum.SmsSendTaskStatus.SMS_WAITING_EXECUTE.getKey();
        //定时发送时间
        Date timingTime = taskType.equals(taskTypeCode)?nowDate:DateUtils.parseDate(req.getTimingTime(),DateUtils.yyyy_MM_ddHHmm);
        //任务发送ip
        String taskSendIp = userTokenInfoVo.getLoginIp();
        //发送任务
        SmsSendTask smsSendTask = new SmsSendTask();
        smsSendTask.setTaskId(taskId);
        smsSendTask.setTaskName(req.getTaskName());
        smsSendTask.setTaskStatusCode(taskStatusCode);
        smsSendTask.setTaskTypeCode(taskTypeCode);
        smsSendTask.setTaskModeCode(req.getTaskModeCode());
        smsSendTask.setTaskSendIp(taskSendIp);
        smsSendTask.setChannelId(smsChannel.getChannelId());
        smsSendTask.setChannelCode(smsChannel.getChannelCode());
        smsSendTask.setChannelName(smsChannel.getChannelName());
        smsSendTask.setChannelIspAttribute(smsChannel.getChannelIspAttribute());
        smsSendTask.setIspId(smsIsp.getIspId());
        smsSendTask.setIspCode(smsIsp.getIspCode());
        smsSendTask.setIspName(smsIsp.getIspName());
        smsSendTask.setIspAttribute(smsIsp.getIspAttribute());
        smsSendTask.setCreateUserId(userId);
        smsSendTask.setCreateTime(nowDate);
        smsSendTask.setUpdateUserId(userId);
        smsSendTask.setUpdateTime(nowDate);
        smsSendTask.setCreateDeptId(createDeptId);
        smsSendTask.setTenantId(userTokenInfoVo.getTenantId());
        smsSendTask.setRemark(req.getRemark());
        smsSendTask.setTimingTime(timingTime);
        smsSendTask.setTemplateId(smsTemplate.getTemplateId());
        smsSendTask.setTemplateName(smsTemplate.getTemplateName());
        smsSendTask.setTemplateCode(smsTemplate.getTemplateCode());
        smsSendTask.setTemplateSign(smsTemplate.getTemplateSign());
        smsSendTask.setTemplateContent(smsTemplate.getContent());
        //插入主表
        smsSendTaskMapper.insertSelective(smsSendTask);
        //批量插入明细
        smsSendTaskDetailMapper.batchInsertListUseAllCols(taskDetailList);
        //立即发送短信
        immediatelySendSms(taskTypeCode,smsSendTask,taskDetailList);
        return ServiceResult.ok(taskId);
    }


    /**
     * 【修改】短信发送任务
     * @param req
     * @return*/
    @KeyLock(lockKeyParts = "taskId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult updateSmsSendTask(UpdateSmsSendTaskReq req) {
        //任务id
        String taskId = req.getTaskId();
        SmsSendTask smsSendTaskOld = smsSendTaskMapper.selectByPrimaryKey(taskId);
        if (smsSendTaskOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //待发送状态
        String waitingSend = SmsEnum.SmsSendTaskStatus.SMS_WAITING_EXECUTE.getKey();
        if (!waitingSend.equals(smsSendTaskOld.getTaskStatusCode())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //检查短信发送任务名称是否重复
        if (!req.getTaskName().equals(smsSendTaskOld.getTaskName())){
            checkSmsSendTaskName(req.getTaskName(),smsSendTaskOld.getTenantId());
        }
        //当前时间
        Date nowDate = new Date();
        //发送内容
        BuildSmsSendTaskDto smsSendTaskDto = buildSmsSendTaskDto(taskId,nowDate,req);
        //待发送明细
        List<SmsSendTaskDetail> taskDetailList = smsSendTaskDto.getSuccessContentList();
        if (taskDetailList.isEmpty()){
            return ServiceResult.fail(ErrorCodes.SMS_SEND_TASK_DETAIL_ERROR);
        }
        //检查短信模板
        SmsTemplate smsTemplate = getSmsTemplateByTemplateId(req.getTemplateId());
        //检查渠道
        SmsChannel smsChannel = getSmsChannelByIspId(smsTemplate.getChannelId());
        //检查服务商是否存在
        SmsIsp smsIsp = getSmsIspByIspId(smsChannel.getIspId());
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前登录人id
        String userId = userTokenInfoVo.getUserId();
        //发送类型
        String taskTypeCode = req.getTaskTypeCode();
        //发送类型
        String taskType = SmsEnum.SmsSendTaskType.SMS_IMMEDIATELY_SEND.getKey();
        //发送状态
        String taskStatusCode = SmsEnum.SmsSendTaskStatus.SMS_WAITING_EXECUTE.getKey();
        //定时发送时间
        Date timingTime = taskType.equals(taskTypeCode)?nowDate:DateUtils.parseDate(req.getTimingTime(),DateUtils.yyyy_MM_ddHHmm);
        //任务发送ip
        String taskSendIp = userTokenInfoVo.getLoginIp();
        //发送任务
        SmsSendTask smsSendTask = new SmsSendTask();
        smsSendTask.setTaskId(taskId);
        smsSendTask.setTaskName(req.getTaskName());
        smsSendTask.setTaskStatusCode(taskStatusCode);
        smsSendTask.setTaskTypeCode(taskTypeCode);
        smsSendTask.setTaskModeCode(req.getTaskModeCode());
        smsSendTask.setTaskSendIp(taskSendIp);
        smsSendTask.setChannelId(smsChannel.getChannelId());
        smsSendTask.setChannelCode(smsChannel.getChannelCode());
        smsSendTask.setChannelName(smsChannel.getChannelName());
        smsSendTask.setChannelIspAttribute(smsChannel.getChannelIspAttribute());
        smsSendTask.setIspId(smsIsp.getIspId());
        smsSendTask.setIspCode(smsIsp.getIspCode());
        smsSendTask.setIspName(smsIsp.getIspName());
        smsSendTask.setIspAttribute(smsIsp.getIspAttribute());
        smsSendTask.setUpdateUserId(userId);
        smsSendTask.setUpdateTime(nowDate);
        smsSendTask.setRemark(req.getRemark());
        smsSendTask.setTimingTime(timingTime);
        smsSendTask.setTemplateId(smsTemplate.getTemplateId());
        smsSendTask.setTemplateName(smsTemplate.getTemplateName());
        smsSendTask.setTemplateCode(smsTemplate.getTemplateCode());
        smsSendTask.setTemplateSign(smsTemplate.getTemplateSign());
        smsSendTask.setTemplateContent(smsTemplate.getContent());
        //插入主表
        smsSendTaskMapper.updateByPrimaryKeySelective(smsSendTask);
        //批量插入明细 先删除后插入
        deleteSmsSendTaskDetailByTaskId(taskId);
        //插入细
        smsSendTaskDetailMapper.batchInsertListUseAllCols(taskDetailList);
        //立即发送短信
        immediatelySendSms(taskTypeCode,smsSendTask,taskDetailList);
        return ServiceResult.ok(taskId);
    }

    /**
     * 【删除】根据短信发送任务id删除任务
     * @param req
     * @return*/
    @KeyLock(lockKeyParts = "taskId")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult deleteSmsSendTaskBySendTaskId(SmsSendTaskIdReq req) {
        //任务id
        String taskId = req.getTaskId();
        SmsSendTask smsSendTaskOld = smsSendTaskMapper.selectByPrimaryKey(taskId);
        if (smsSendTaskOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //待发送状态
        String waitingSend = SmsEnum.SmsSendTaskStatus.SMS_WAITING_EXECUTE.getKey();
        if (!waitingSend.equals(smsSendTaskOld.getTaskStatusCode())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //删除主表
        smsSendTaskMapper.deleteByPrimaryKey(taskId);
        //删除明细表
        deleteSmsSendTaskDetailByTaskId(taskId);
        return ServiceResult.ok(taskId);
    }


    /**
     * 【分页查询】根据短信发送任务id分页查询发送任务明细
     * @param req
     * @return*/
    @Override
    public ServiceResult<PageResult<List<QuerySmsSendTaskDetailRes>>> querySmsSendTaskDetailResList(QuerySmsSendTaskDetailReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sendTime desc, detailId desc");
        List<QuerySmsSendTaskDetailRes> list = smsSendTaskDetailMapper.querySmsSendTaskDetailResListByTaskId(req.getTaskId());
        for (QuerySmsSendTaskDetailRes res:list){
            SystemDict sendStatusCode = systemDictCache.getSystemDictByDictCode(res.getSendStatusCode());
            res.setSendStatusName(sendStatusCode.getDictName());
            res.setSendStatusColor(sendStatusCode.getDictColor());
        }
        return PageHelperUtil.returnServiceResult(req, list);
    }


    /**
     * 执行短信发送任务
     */
    @Override
    public void executeSmsSendTask() {
        //当前时间
        Date nowDate = new Date();
        //查询所有待发送的任务
        List<SmsSendTask> smsSendTaskList = smsSendTaskMapper.queryAllWaitingSendSmsSendTaskList(DateUtils.dateToString(nowDate));
        //查询所有等待发送任务明细集合
        List<SmsSendTaskDetail> taskDetailList = smsSendTaskDetailMapper.queryAllWaitingSendSmsSendTaskDetailList();
        //执行类型
        String taskType = SmsEnum.SmsSendTaskType.SMS_TIMING_SEND.getKey();
        //执行任务
        smsSendTask(nowDate,taskType,smsSendTaskList,taskDetailList);
    }

    /**
     * 获取短信渠道
     * @param channelId
     */
    private SmsChannel getSmsChannelByIspId(String channelId){
        if (StringUtils.isBlank(channelId)){
            throw new DuoJuHeException(ErrorCodes.SMS_CHANNEL_NOT_EXIST);
        }
        SmsChannel smsChannel = smsChannelMapper.selectByPrimaryKey(channelId);
        if (smsChannel==null || !SystemEnum.STATUS.NORMAL.getKey().equals(smsChannel.getStatusCode())){
            throw new DuoJuHeException(ErrorCodes.SMS_CHANNEL_NOT_EXIST);
        }
        return smsChannel;
    }
    /**
     * 获取短信服务商
     * @param ispId
     */
    private SmsIsp getSmsIspByIspId(String ispId){
        if (StringUtils.isBlank(ispId)){
            throw new DuoJuHeException(ErrorCodes.SMS_ISP_NOT_EXIST);
        }
        SmsIsp smsIsp = smsIspMapper.selectByPrimaryKey(ispId);
        if (smsIsp==null || !SystemEnum.STATUS.NORMAL.getKey().equals(smsIsp.getStatusCode())){
            throw new DuoJuHeException(ErrorCodes.SMS_ISP_NOT_EXIST);
        }
        return smsIsp;
    }

    /**
     * 获取短信模板信息
     * @param templateId
     */
    private SmsTemplate getSmsTemplateByTemplateId(String templateId){
        if (StringUtils.isBlank(templateId)){
            throw new DuoJuHeException(ErrorCodes.SMS_TEMPLATE_NOT_EXIST);
        }
        SmsTemplate smsTemplate = smsTemplateMapper.selectByPrimaryKey(templateId);
        if (smsTemplate==null){
            throw new DuoJuHeException(ErrorCodes.SMS_TEMPLATE_NOT_EXIST);
        }
        return smsTemplate;
    }
    /**
     * 根据短信发送任务id删除明细
     * @param taskId
     */
    private void deleteSmsSendTaskDetailByTaskId(String taskId){
        if (StringUtils.isBlank(taskId)){
            return;
        }
        SmsSendTaskDetail deleteSmsSendTaskDetail = new SmsSendTaskDetail();
        deleteSmsSendTaskDetail.setTaskId(taskId);
        smsSendTaskDetailMapper.delete(deleteSmsSendTaskDetail);
    }


    /**
     * 【私有方法，辅助其他接口方法使用】 查询短信发送任务名称是否已经存在
     */
    private void checkSmsSendTaskName(String taskName,String tenantId) {
        if (StringUtils.isBlank(taskName)||StringUtils.isBlank(tenantId)){
            throw new DuoJuHeException(ErrorCodes.SMS_SEND_TASK_NAME_EXIST);
        }
        Example example = new Example(SmsSendTask.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("taskName", taskName);
        criteria.andEqualTo("tenantId", tenantId);
        if(smsSendTaskMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.SMS_SEND_TASK_NAME_EXIST);
        }
    }



    /**
     * 构建发送内容
     * @param nowDate
     * @param req
     * @return
     */
    private BuildSmsSendTaskDto buildSmsSendTaskDto(String taskId,Date nowDate,SaveSmsSendTaskReq req){
        //错误和重复的数据如下
        List<String> errorTaskContentList = new ArrayList<>();
        //待处理的内容map
        HashMap<String, SmsSendTaskDetail> contentMap = new HashMap<>();
        //检查发送内容
        Date timingTime = DateUtils.parseDate(req.getTimingTime(),DateUtils.yyyy_MM_ddHHmm);
        //发送类型
        String taskType = SmsEnum.SmsSendTaskType.SMS_IMMEDIATELY_SEND.getKey();
        //明细发送状态
        String sendStatusCode = SmsEnum.SmsSendStatus.SMS_SEND_WAITING.getKey();
        if (!taskType.equals(req.getTaskTypeCode())){
            if (timingTime==null||timingTime.getTime()<=nowDate.getTime()){
                throw new DuoJuHeException(ErrorCodes.SMS_SEND_TASK_TIMING_TIME_ERROR);
            }
        }else{
            sendStatusCode = SmsEnum.SmsSendStatus.SMS_SEND_SENDING.getKey();
        }
        //检查发送内容
        if (SmsEnum.SmsSendTaskMode.SMS_CUSTOM_MODE.getKey().equals(req.getTaskModeCode())){
            List<String> taskContentList = req.getTaskContentList();
            for (String mobile:taskContentList){
                if (!RegexUtil.isMobile(mobile)){
                    throw new DuoJuHeException(mobile+"号码格式错误，请仔细检查发送手机号码格式!");
                }
                if (!contentMap.containsKey(mobile)){
                    SmsSendTaskDetail taskDetail = new SmsSendTaskDetail();
                    taskDetail.setDetailId(UUIDUtils.getUUID32());
                    taskDetail.setTaskId(taskId);
                    taskDetail.setMobileNumber(mobile);
                    taskDetail.setCreateTime(nowDate);
                    taskDetail.setSendStatusCode(sendStatusCode);
                    contentMap.put(mobile,taskDetail);
                }else {
                    errorTaskContentList.add(mobile);
                }
            }
        }else {
            throw new DuoJuHeException("该发送模式正在开发中!");
        }
        //成功的数据
        List<SmsSendTaskDetail> successTaskContentList = new ArrayList<>(contentMap.values());
        BuildSmsSendTaskDto smsSendTaskDto = new BuildSmsSendTaskDto();
        smsSendTaskDto.setErrorTaskContentList(errorTaskContentList);
        smsSendTaskDto.setSuccessContentList(successTaskContentList);
        return smsSendTaskDto;
    }


    /**
     * 处理返回值的数据字典
     * @param res
     */
    private void setHandleSmsSendTaskDictNameColor(HandleSmsSendTaskDictNameColorRes res) {
        if (res==null){
            return;
        }
        SystemDict taskStatusCode = systemDictCache.getSystemDictByDictCode(res.getTaskStatusCode());
        res.setTaskStatusName(taskStatusCode.getDictName());
        res.setTaskStatusColor(taskStatusCode.getDictColor());

        SystemDict taskTypeCode = systemDictCache.getSystemDictByDictCode(res.getTaskTypeCode());
        res.setTaskTypeName(taskTypeCode.getDictName());
        res.setTaskTypeColor(taskTypeCode.getDictColor());

        SystemDict taskModeCode = systemDictCache.getSystemDictByDictCode(res.getTaskModeCode());
        res.setTaskModeName(taskModeCode.getDictName());
        res.setTaskModeColor(taskModeCode.getDictColor());
    }




    /**
     * 立即发送短信
     * @param taskTypeCode
     * @param smsSendTask
     * @param taskDetailList
     */
    private void immediatelySendSms(String taskTypeCode,SmsSendTask smsSendTask,List<SmsSendTaskDetail> taskDetailList){
        //当前时间
        Date nowDate = new Date();
        //发送类型
        String taskType = SmsEnum.SmsSendTaskType.SMS_IMMEDIATELY_SEND.getKey();
        //如果是立即发送短信类型则执行以下方法
        if (taskType.equals(taskTypeCode)){
            smsSendTask(nowDate,taskType,Collections.singletonList(smsSendTask),taskDetailList);
        }
    }



    /**
     * 执行短信发送线程
     * @param sendTaskList
     * @param taskDetailList
     */
    private void smsSendTask(Date nowDate,String taskType,List<SmsSendTask> sendTaskList,List<SmsSendTaskDetail> taskDetailList){
        for (SmsSendTask newSmsSendTask:sendTaskList){
            String taskId = newSmsSendTask.getTaskId();
            try {
                if (!RedisSonLockUtils.fairTryLock(taskId)){
                    log.info("【短信发送任务】获取锁失败，跳过本次执行，key={}", taskId);
                    continue;
                }
                log.info("【短信发送任务】获取锁成功key={}", taskId);

                //定时发送类型
                String smsTimingSend = SmsEnum.SmsSendTaskType.SMS_TIMING_SEND.getKey();
                if (smsTimingSend.equals(taskType)){
                    newSmsSendTask = smsSendTaskMapper.selectByPrimaryKey(taskId);
                }
                if (newSmsSendTask==null){
                    continue;
                }
                //当前任务状态
                String taskStatusCode = newSmsSendTask.getTaskStatusCode();
                //待发送状态
                String waitingSend = SmsEnum.SmsSendTaskStatus.SMS_WAITING_EXECUTE.getKey();
                //发送任务
                if (!waitingSend.equals(taskStatusCode)){
                    continue;
                }
                //更新任务表 设置成已执行
                SmsSendTask updateSmsSendTask = new SmsSendTask();
                updateSmsSendTask.setTaskId(taskId);
                updateSmsSendTask.setTaskExecuteTime(nowDate);
                updateSmsSendTask.setTaskStatusCode(SmsEnum.SmsSendTaskStatus.SMS_ALREADY_EXECUTE.getKey());
                smsSendTaskMapper.updateByPrimaryKeySelective(updateSmsSendTask);
                //分发短信发送任务
                distributeSendSms(nowDate,newSmsSendTask,taskDetailList);
            }catch (Exception e){
                log.error("【短信发送任务】出现异常",e);
            }finally {
                log.info("【短信发送任务】释放锁key={}",taskId);
                RedisSonLockUtils.unlock(taskId);
            }
        }
    }

    /**
     * 执行短信发送
     * @param smsSendTask
     * @param taskDetailList
     */
    private void distributeSendSms(Date nowDate,SmsSendTask smsSendTask,List<SmsSendTaskDetail> taskDetailList){
        //短信服务厂商
        String isp = smsSendTask.getIspCode();
        //任务id
        String taskId = smsSendTask.getTaskId();
        //从明细集合中取出当前任务的明细集合
        List<SmsSendTaskDetail> detailList = taskDetailList.stream().filter(e->taskId.equals(e.getTaskId())).collect(Collectors.toList());
        if (SmsEnum.SmsIsp.aliyun.getKey().equals(isp)){
            //异步发送短信
            ThreadUtils.execute(() -> aliYun(nowDate,smsSendTask,detailList));
        }
    }


    /**
     * 阿里云短信服务商发送
     * @param nowDate
     * @param smsSendTask
     * @param detailList
     */
    private void aliYun(Date nowDate,SmsSendTask smsSendTask,List<SmsSendTaskDetail> detailList){
       try{
           //渠道配置
           String channelIspAttribute = smsSendTask.getChannelIspAttribute();
           //请求参数的填写的值
           List<AttributeParameter> ispAttributeParameters = JSON.parseObject(channelIspAttribute, new TypeReference<ArrayList<AttributeParameter>>(){});
           //请求参数转成map
           Map<String, AttributeParameter> attributeMap = ispAttributeParameters.stream().collect(Collectors.toMap(AttributeParameter::getKey, a -> a));
           //创建部门id
           String createDeptId = smsSendTask.getCreateDeptId();
           //创建用户id
           String createUserId = smsSendTask.getCreateUserId();
           //租户id
           String tenantId = smsSendTask.getTenantId();
           //模板编码
           String templateCode = smsSendTask.getTemplateCode();
           //发送ip
           String sendIp = smsSendTask.getTaskSendIp();
           //短信签名
           String smsSign = smsSendTask.getTemplateSign();
           //扩展参数
           String templateParam = "";
           //短信内容
           String templateContent = smsSendTask.getTemplateContent();
           //短信发送服务商id
           String ispId = smsSendTask.getIspId();
           //短信发送服务商编码
           String ispCode = smsSendTask.getIspCode();
           //短信发送渠道id
           String channelId = smsSendTask.getChannelId();

           //接口账号
           AttributeParameter appIdAttribute = attributeMap.get("appId");
           String account = appIdAttribute!=null?appIdAttribute.getValue():"";
           //接口密码
           AttributeParameter appKeyAttribute = attributeMap.get("appKey");
           String password = appKeyAttribute!=null?appKeyAttribute.getValue():"";
           for (SmsSendTaskDetail taskDetail:detailList){
               //手机号码
               String mobile = taskDetail.getMobileNumber();
               //暂时休眠，便于后期其他方式调优
               Thread.sleep(300L);
               //构建短信发送对象
               SmsRepeatRecordDto repeatRecordDto = new SmsRepeatRecordDto();
               repeatRecordDto.setMobileNumber(mobile);
               repeatRecordDto.setSmsSendIp(sendIp);
               repeatRecordDto.setSendNumber(1);
               repeatRecordDto.setTemplateCode(templateCode);
               repeatRecordDto.setTemplateContent(templateContent);
               repeatRecordDto.setTemplateParam(templateParam);
               repeatRecordDto.setSignName(smsSign);
               repeatRecordDto.setChannelAccount(account);
               repeatRecordDto.setChannelPassword(password);
               repeatRecordDto.setCreateDeptId(createDeptId);
               repeatRecordDto.setCreateUserId(createUserId);
               repeatRecordDto.setTenantId(tenantId);
               repeatRecordDto.setSendTaskId(smsSendTask.getTaskId());
               repeatRecordDto.setSendTaskDetailId(taskDetail.getDetailId());
               repeatRecordDto.setChannelId(channelId);
               repeatRecordDto.setIspId(ispId);
               repeatRecordDto.setIspCode(ispCode);
               //调用短信发送
               handlerSmsService.aliYunSms(nowDate,repeatRecordDto);
           }
       }catch (Exception e){
            log.error("【短信发送任务】阿里云短信服务商发送出现异常",e);
       }
    }
}
